package en.edu.lzzy.bookmanagement.service;

import en.edu.lzzy.bookmanagement.model.Book;
import en.edu.lzzy.bookmanagement.model.Category;
import en.edu.lzzy.bookmanagement.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Repository
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    // 获取数据库中的所有Category记录，然后返回一个Category列表
    public List<Category> getAllCategories() {
        return categoryRepository.findAll();
    }

    @Override
    // 将传入的Category对象保存到数据库中
    public void saveCategory(Category category) {
        categoryRepository.save(category);
    }

    @Override
    // 通过调用categoryRepository的findById()方法查询对应的Category记录，并返回该记录。如果查询不到对应的记录，则返回null
    public Category getCategoryById(long id) {
        return categoryRepository.findById(id).orElse(null);
    }

    @Override
    // 通过调用categoryRepository的deleteById()方法删除对应的Category记录
    public void deleteCategoryById(long id) {
        categoryRepository.deleteById(id);
    }

//    @Override
//    public List<Book> getBooksByCategoryId(long categoryId) {
//        Category category = categoryRepository.findById(categoryId).orElse(null);
//        if (category != null) {
//            return category.getBooks();
//        } else {
//            return null;
//        }
//    }

    @Override
    // 如果查到了该记录，则获取其关联的Book列表，并根据传入的分页参数进行分页处理，最后返回一个Page<Book>对象。如果未查到对应的Category记录，则返回一个空的Page对象
    public Page<Book> getBooksByCategoryId(long categoryId, Pageable pageable) {
        Optional<Category> categoryOptional = categoryRepository.findById(categoryId);
        if (categoryOptional.isPresent()) {
            Category category = categoryOptional.get();
            List<Book> books = category.getBooks();

            // 创建一个分页请求
            int pageSize = pageable.getPageSize();
            int currentPage = pageable.getPageNumber();
            int startItem = currentPage * pageSize;

            List<Book> pagedBooks;
            if (books.size() < startItem) {
                pagedBooks = Collections.emptyList();
            } else {
                int toIndex = Math.min(startItem + pageSize, books.size());
                pagedBooks = books.subList(startItem, toIndex);
            }

            return new PageImpl<>(pagedBooks, pageable, books.size());
        } else {
            return Page.empty();
        }
    }

}
